package cn.easyar.samples.helloarqrcode.xunfei;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

import cn.easyar.samples.helloarqrcode.MainActivity;

public class VoiceService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        AudioRecordManager.getInstance().startRecord(getExternalCacheDir().getAbsolutePath() + File.separator + "qc_save" + File.separator + "qc");
        new Thread(new Runnable() {
            @Override
            public void run() {
                mySend();
            }
        }).start();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //----------------------------------------------------
    // appid
    private static final String APPID = "5c80ab54";

    // appid对应的secret_key
    private static final String SECRET_KEY = "06003d2807b5d96d387e71db0b4f5547";

    // 请求地址
    private static final String HOST = "rtasr.xfyun.cn/v1/ws";

    private static final String BASE_URL = "ws://" + HOST;

    private static final String ORIGIN = "http://" + HOST;

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
    private RTASRTest.MyWebSocketClient client;

    private void mySend(){
        while (true) {
            URI url = null;
            try {
                url = new URI(BASE_URL + getHandShakeParams(APPID, SECRET_KEY));
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            DraftWithOrigin draft = new DraftWithOrigin(ORIGIN);
            CountDownLatch handshakeSuccess = new CountDownLatch(1);
            CountDownLatch connectClose = new CountDownLatch(1);
            client = new RTASRTest.MyWebSocketClient(url, draft, handshakeSuccess, connectClose);

            client.connect();
            client.setOnVoiceBack(new RTASRTest.MyWebSocketClient.OnVoiceBack() {
                @Override
                public void onBack(String str) {
                    EventBus.getDefault().post(new VoiceBean(str));
                    System.out.print(VoiceOrder.activityList.get(VoiceOrder.activityList.size()-1)+"--------------------");
                }
            });

            while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                System.out.println(getCurrentTimeStr() + "\t连接中");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 等待握手成功
            try {
                handshakeSuccess.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(sdf.format(new Date()) + " 开始发送音频数据");
            // 发送音频
            byte[] bytes = AudioRecordManager.getInstance().mBuffer;
            int len = -1;
            long lastTs = 0;
            while (bytes != null) {
//                    if (len < CHUNCKED_SIZE) {
//                        send(client, bytes = Arrays.copyOfRange(bytes, 0, len));
//                        break;
//                    }

                long curTs = System.currentTimeMillis();
                if (lastTs == 0) {
                    lastTs = System.currentTimeMillis();
                } else {
                    long s = curTs - lastTs;
                    if (s < 40) {
                        System.out.println("error time interval: " + s + " ms");
                    }
                }

//                    send(client, bytes);
                send(client, AudioRecordManager.getInstance().mBuffer);
                // 每隔40毫秒发送一次数据
                try {
                    Thread.sleep(40);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 发送结束标识
            send(client,"{\"end\": true}".getBytes());
            System.out.println(getCurrentTimeStr() + "\t发送结束标识完成");

            // 等待连接关闭
            try {
                connectClose.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            break;
        }
    }

    // 生成握手参数
    public static String getHandShakeParams(String appId, String secretKey) {
        String ts = System.currentTimeMillis()/1000 + "";
        String signa = "";
        try {
            signa = EncryptUtil.HmacSHA1Encrypt(EncryptUtil.MD5(appId + ts), secretKey);
            return "?appid=" + appId + "&ts=" + ts + "&signa=" + URLEncoder.encode(signa, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void send(WebSocketClient client, byte[] bytes) {
        if (client.isClosed()) {
            throw new RuntimeException("client connect closed!");
        }

        client.send(bytes);
    }

    public static String getCurrentTimeStr() {
        return sdf.format(new Date());
    }
}
